FILE I/O

Binary I/O (OLD NOTES)

std::ifstream ifs(argv[1], std::ios::in | std::ios::binary | std::ios::ate );
//ifs.seekg(0, std::ios::end);
size_t byte_count = ifs.tellg();
ifs.seekg(0, std::ios::beg);
std::cout << "file size: " << byte_count << std::endl;
char *pb = new char [byte_count];
ifs.read(pb, byte_count);

std::ofstream ofs(argv[2], std::ios::out | std::ios::binary);
ofs.write(pb, byte_count);
ofs.close();

delete[] pb;

ifs.close();

PRELIMINARY SHIT

First, of course, you gotta include the necessary headers.

#include <fstream> // No .h extension

So, the fstream header contains defs for two types, std::ifstream and std::ofstream. (An easy way to remember this is the originals are istream and ostream, so just add an f before the "stream")


FILE OUTPUT

Output example

  std::ofstream outfile;   // instantiate output file
  outfile.open("foo.txt"); // associate a disk file

    // Write some data to the file
  outfile << "This is a line of text" << std::endl;
  outfile << "Another line of text" << std::endl;
  outfile << "An integer: " << 42 << std::endl;
  outfile << "A double: " << 3.1415 << std::endl;

  outfile.close(); // close the file [optional]

Note: For automatic, stack-based objects, we don't need to call close since it will be done in the destructor.


remember to check whether the file is open....

  if(!outfile.is_open())

FILE INPUT

void f5(void)
{
  std::ifstream infile("foo.txt");
  if (!infile.is_open())
    std::cout << "Can't open file.\n";
  else
  {
    std::string str;
    while (!infile.eof())
    {
      infile >> str;
      std::cout << str << std::endl;
    }
  }
}
void f11(void)
{
  std::ifstream infile("foo.txt");
  if (!infile.is_open())
    std::cout << "Can't open file.\n";
  else
  {
    std::string str;
    while (!infile.eof())
    {
      if (std::getline(infile, str).eof())
        break;
      std::cout << str << std::endl;
    }
  }
}

Some modes and their usages

Mode Meaning
ios_base::in Open file for input (default for ifstream)
ios_base::out Open file for output (default for ofstream)
ios_base::app Seek to the end before each write
ios_base::trunc Truncate file (delete contents) after opening (default for ofstream)
ios_base::ate Seek to the end once after opening
ios_base::binary Open file in binary mode